package com.minshenglife.zanzan.web.weixin;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.minshenglife.zanzan.entity.AccessToken;
import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.pub.utils.Message;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.service.AccessTokenService;
import com.minshenglife.zanzan.service.UserService;
import com.nationsky.pub.framework.exception.GenericException;
import com.nationsky.pub.utils.GsonUtils;
import com.nationsky.pub.utils.StringUtils;

/**
 * 
 * @author huodd
 * 
 */
public class AccessTokenFilter implements  Filter  {
	Logger log = LoggerFactory.getLogger(AccessTokenFilter.class);
	private  AccessTokenService accessTokenService;
	private  UserService userService;
	
	
	public AccessTokenService getAccessTokenService() {
		return accessTokenService;
	}

	public void setAccessTokenService(AccessTokenService accessTokenService) {
		this.accessTokenService = accessTokenService;
	}

	
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain filterChain) throws IOException, ServletException {
		
		HttpServletRequest request=(HttpServletRequest)arg0;
		HttpServletResponse response=(HttpServletResponse)arg1;
		
		//直接跳转：
		//filterChain.doFilter(request, response);
		
		log.debug("=============过滤了===========");
		
		String url=request.getRequestURI();
		log.debug("上送的url："+url);
		String token=request.getParameter("access_token");
		String userPostId=request.getParameter("userPostId");
		boolean isJsp=false;//
		String errorPage=WXKeys.WX_BASEURL+"/jsp/error/error.html";
		String promptPage=WXKeys.WX_BASEURL+"/jsp/error/prompt.jsp";
		Integer error_code=444;//过滤错误专属标识
		
		String method = request.getMethod();
		
		String user_agent=request.getHeader("User-Agent");
		
		log.debug("access_token: "+token);
		log.debug("user_agent: "+user_agent);
		if(url.endsWith(".jsp") || url.endsWith(".html") ){
			log.debug("请求的是jsp页面");
			isJsp=true;
		}
		if(!(method.equals("GET")||method.equals("POST"))){
			log.debug("非GET或POST请求");
			response.sendRedirect(errorPage);
			return;
		}
		if(url.endsWith("toYunZhuLI.do")){
			request.getSession().setAttribute("rsource", "Y");
		}
		System.out.println(request.getSession().getAttribute("rsource"));
		request.getSession().setMaxInactiveInterval(1800);
		if(url.endsWith("main.do") || url.endsWith("toPageDoor.do") || url.endsWith("createMenu.do")||url.endsWith("saveAccessToken.do") 
				|| url.endsWith("initDeptInfo.do") || url.endsWith("initEmpInfo.do") || url.endsWith("toWebPageDoor.do")||url.endsWith("getTicket.do")||url.endsWith("toYunZhuLI.do")){//放行
			filterChain.doFilter(request, response);
		}else{
		
			if(!StringUtils.isNullOrEmpty(token)){
				AccessToken accessToken=new AccessToken();
				accessToken.setAccessToken(token);
				//根据tokenId 获取、AccessToken对象
				accessToken=accessTokenService.getAccessTokenByToken(accessToken);
				if(accessToken!=null){
//					if( new Date().getTime()>accessToken.getEnd_time().getTime()){ //大于30分钟
//						//大于时效的处理
//						log.debug("大于30分钟了");
//						//如果是.jsp的页面，重定向到页面已失效页面
//						log.debug("request.getContentType() :"+request.getContentType());
//						if(isJsp){
//							log.debug(errorPage);
//							response.sendRedirect(errorPage);
//							return;
//						}else{
//							//如果是异步请求 ,返回已失效页面 Message json字符串
//							writeJson(response,new Message(Message.STATE_one,"页面已失效"));
//							return;
//						}
//					}
//				else{
						log.debug("小于30分钟了");
						String empId=accessToken.getEmpId();
						User user=null;
						boolean con=true;
						log.debug("empId="+empId);
						if(!StringUtils.isNullOrEmpty(empId)){
							user=userService.getUserInfo(empId);
//							String notCheckUser = Config.getProperty("notCheckUser");
							if(user!=null){
//								log.debug("当前用户是否是指定用户： "+notCheckUser.indexOf(user.getEmpId()));
//								log.debug("==="+(url.indexOf("workCon.jsp") != -1)+"==="+(url.indexOf("workConList.jsp") != -1 ) );
								//针对工作日志页面进行限制，指定用户可以直接通过
//								if(url.indexOf("workCon.jsp") != -1 || url.indexOf("workConList.jsp") != -1 ){
//									if(notCheckUser.indexOf(user.getEmpId()) != -1){
//										
//									}else{
//										String prompt="抱歉，此菜单只对指定员工开放，请离开！";
//										con=false;
//										toPrompt(response, isJsp, promptPage,prompt);
//										return;
//									}
////								}
//								if(notCheckUser.indexOf(user.getEmpId()) != -1){
////									String prompt="抱歉，此菜单只对指定员工开放，请离开！";
////									con=false;
////									toPrompt(response, isJsp, promptPage,prompt);
////									return;
//								}
//								//校验用户的机构名称是否包含“总公司”，
//								else if(user.getDeptName().startsWith("总公司") || "false".equals(Config.getProperty("isLimitBranch"))){
//									
//								}
//								else{//不是总公司的禁止使用
//									String prompt="此微信暂时只对民生总公司开放，非总公司员工，请自觉离开！";
//									con=false;
//									toPrompt(response, isJsp, promptPage,prompt);
//									return;
//								}
							}
						}
						if(con){
							request.setAttribute("openId",accessToken.getOpenId());
							request.setAttribute("empId",accessToken.getEmpId());
							log.debug("存储empId："+accessToken.getEmpId());
							request.setAttribute("accessToken",accessToken.getAccessToken());
							
							if(userPostId!=null&&userPostId.trim().length()!=0){
								userPostId = userPostId.trim().toUpperCase();
								String thisEmpPostId = user.getPostId().trim().toUpperCase();
								if(!thisEmpPostId.equals(userPostId)){
									log.debug("传递的PostId:"+userPostId+"与实际的PostId:"+thisEmpPostId+"不一致！");
									//如果是.jsp的页面，重定向到页面已失效页面
									if(isJsp){
										log.debug(errorPage);
										response.sendRedirect(errorPage);
										return;
									}
									else{
										//如果是.do ,返回已失效页面 Message json字符串
										writeJson(response,new Message(Message.STATE_one,"非法访问，如需帮助请联系管理员",error_code));
									}
								}
							}
							
							filterChain.doFilter(request, response);
						}
//					}
				}else{
					log.debug("access_token查不到用户数据");
					if(isJsp){
						log.debug(errorPage);
						response.sendRedirect(errorPage);
						return;
					}else{
						writeJson(response,new Message(Message.STATE_one,"非法访问，如需帮助请联系管理员",error_code));
						return;
					}
				}
			}else{ //如果没有取到token
				log.debug("没有取到access_token");
				//如果是.jsp的页面，重定向到页面已失效页面
				if(isJsp){
					log.debug(errorPage);
					response.sendRedirect(errorPage);
					return;
				}
				else{
					//如果是.do ,返回已失效页面 Message json字符串
					writeJson(response,new Message(Message.STATE_one,"非法访问，如需帮助请联系管理员",error_code));
				}
			}
		}

	}

	private void toPrompt(HttpServletResponse response, boolean isJsp,
			String promptPage, String prompt) throws IOException {
		if(isJsp){
			log.debug(promptPage);
			response.sendRedirect(promptPage);
			return;
		}else{
			//如果是异步请求 ,返回已失效页面 Message json字符串
			writeJson(response,new Message(Message.STATE_one,prompt));
			return;
		}
	}

	
	@Override
	public void init(FilterConfig config) throws ServletException {
		ServletContext context = config.getServletContext();  
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);  
		accessTokenService = (AccessTokenService) ctx.getBean("accessTokenServiceImpl");
		userService = (UserService) ctx.getBean("userServiceImpl");
	}
	@Override
	public void destroy() {

	}

	 /**
     * 将obj转换成json数据格式并写会response中
     * 
     * @param response
     * @param obj
     * @throws GenericException
     */
    private void writeJson(HttpServletResponse response, Object obj)
    {
        String jsonStr = GsonUtils.toGson(obj);
        log.debug("--->" + jsonStr);
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");

        try
        {
            response.getWriter().write(jsonStr);
            response.getWriter().flush();
            response.getWriter().close();
        }
        catch(IOException e)
        {
            log.error("write json to response error: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
}
